package SpaceIT.pages;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import model.dao.ChiTietHoaDonDAO;
import model.dao.HoaDonDAO;
import model.dao.PaypalDAO;
import model.pojo.ChiTietHoaDon;
import model.pojo.HoaDon;
import model.pojo.Paypal;
import model.pojo.ThongTinKhachHang;
import model.util.paypalfunctions;

import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Response;
import org.apache.tapestry5.services.Session;
import org.apache.tools.ant.taskdefs.rmic.KaffeRmic;

public class confirm {

	@Inject
	private Request request;
	@Inject
	private Response response;
	
	@Property
	private  HashMap nvp; 
	@ApplicationState
	private model.pojo.Cart arrGioHang;
	@ApplicationState
	private ThongTinKhachHang ttKH;
	
	public boolean isS()
	{
		String strAck = nvp.get("ACK").toString();
		if(strAck.equalsIgnoreCase("Success") )
		{
			//insert CSDL
			HoaDon hd = new HoaDon();
			hd.setKhachHang(ttKH);
			Date todayD=new Date(System.currentTimeMillis()); 
            SimpleDateFormat dayFormat= new SimpleDateFormat("dd/MM/yyyy"); 
            String todayS=dayFormat.format(todayD.getTime()); 
			hd.setNgayLapHD(todayS);
			hd.setSoLuongSP(arrGioHang.SoLuong());
			hd.setTongTienTT(arrGioHang.TongTien());
			
			boolean kqInS = HoaDonDAO.ThemHoaDon(hd);
			if(kqInS==true)
			{
				for(int i =0 ;i < arrGioHang.Size() ; i++)
				{
					ChiTietHoaDon ct = new ChiTietHoaDon();
					ct.setMaHD(hd.getMaHD());
					ct.setMaSP(arrGioHang.get(i).getMaSP());
					ct.setSoLuong(arrGioHang.get(i).getSoLuong());
					
					boolean kqInSCt = ChiTietHoaDonDAO.ThemChiTietHoaDon(ct);
					if(kqInSCt==false)
					{
						return false;
					}
				}
				arrGioHang.RemoveAll();
				return true;
			}
		}
		return false;
	}
	
	public void onActivate()
	{
			nvp =null;
			
		  	Session session = request.getSession(true);
			String token =  session.getAttribute("TOKEN").toString();
	
			if ( token != null)
			{			
				String serverName =  request.getServerName();
				String payerId =  session.getAttribute("PAYERID").toString();
				//String token =  session.getAttribute("token").toString();
				String finalPaymentAmount =  session.getAttribute("Payment_Amount").toString();
				Paypal pp = PaypalDAO.LayThongTinPaypal();
				paypalfunctions ppf = new paypalfunctions(pp);
				nvp = ppf.ConfirmPayment ( token, payerId, finalPaymentAmount, serverName );
			      
			}
	}
	
	
}
